import { createI18n } from 'vue-i18n'
import { getLanguage } from '@/utils/cookies'

// element-ui built-in lang
import elementEnLocale from 'element-plus/lib/locale/lang/en'
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn'

// User defined lang
import enLocale from './en'
import zhLocale from './zh-cn'

const messages = {
  en: {
    el: elementEnLocale.el,
    app: {
      ...enLocale
    }
  },
  'zh-cn': {
    el: elementZhLocale.el,
    app: {
      ...zhLocale
    }
  },

}

export const getLocale = () => {
  const cookieLanguage = getLanguage()
  if (cookieLanguage) {
    document.documentElement.lang = cookieLanguage
    return cookieLanguage
  }

  const language = navigator.language.toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale
      return locale
    }
  }
  // Default language is chinese
  return 'zh-cn'
}

/**
 * 注册i18n实例并引入语言文件
 */
const i18n = createI18n({
  // 默认语言，存入cookies
  locale: getLocale(),
  fallbackLocale: 'zh-cn',
  globalInjection: true,
  messages,
})

export default i18n